package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/2103A/message/goods"
	"wsyxapi/client"

	"wsyxapi/internal/svc"
	"wsyxapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserStartGoodLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateUserStartGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserStartGoodLogic {
	return &CreateUserStartGoodLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateUserStartGoodLogic) CreateUserStartGood(req *types.CreateUserStarGoodRequest) (resp *types.CreateUserStarGoodResponse, err error) {
	value := l.ctx.Value("id")
	valStr := value.(json.Number)
	userID, err := valStr.Int64()
	if err != nil {
		return nil, err
	}

	if req.GoodSKUID == 0 {
		return nil, err
	}

	// TODO:需要验证用户信息

	exits, err := client.ExistGoodsSkuById(context.Background(), &goods.GetGoodsSkuByIdRequest{Id: int32(req.GoodSKUID)})
	if err != nil {
		return nil, err
	}
	if !exits {
		return nil, fmt.Errorf("商品sku不存在：sku_id:%v", req.GoodSKUID)
	}

	// TODO:完成Good接口实现
	goodInfo := client.GetGoodsSkuById()

	info, err := client.CreateUserStarGood(context.Background(), userID, req.GoodSKUID)
	if err != nil {
		return nil, err
	}

	var infos []types.GoodSKU
	infos = append(infos, types.GoodSKU{
		GoodSKUID:  info.GoodSKUID,
		GoodName:   goodInfo.Name,
		GoodePrice: goodInfo.Price,
		Imgae:      goodInfo.Image,
	})

	return &types.CreateUserStarGoodResponse{
		GoodSKUList: infos,
	}, nil
}
